//
//  YDPhotoController.swift
//  YDPhotoPicker
//
//  Created by alyadan on 16/7/31.
//  Copyright © 2016年 alyadan. All rights reserved.
//

import UIKit
import MVVM_BaseViewController
import YD_Util
import Photos

public class YDPhotoController: MVVM_BaseViewController {

    
    let tableView:UITableView = UITableView()
    
    override public var currentModel: YDPhotoVCModel{
       return vcModel.value as! YDPhotoVCModel
    }
    
    
    
    override public func setupUI() {
        super.setupUI()
        self.automaticallyAdjustsScrollViewInsets = false
        
        tableView.delegate = currentModel
        tableView.dataSource = currentModel
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: currentModel.albumCellID)
        view.addSubview(tableView)
        
        tableView.snp.makeConstraints {[unowned self] (ConstraintMaker) in
            ConstraintMaker.top.equalTo(self.topLayoutGuide.snp.bottom)
            ConstraintMaker.left.right.bottom.equalTo(self.view)
        }
    }

//    override public func viewDidLayoutSubviews() {
//       tableView.frame = view.bounds
//    }
    override public func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    


}

import Photos

public protocol cropImageProtocol {
    func cropImage(image:UIImage)
}

public class YDPhotoVCModel: MVVM_BaseVCModel ,UITableViewDataSource, UITableViewDelegate{
    var assetCollectResult = [PHAssetCollection]()
    var assetsResult = [PHFetchResult<AnyObject>]()
    public typealias CompleteWithAssetsBlock = (_ selectedAsset:[PHAsset]) -> Void
    public typealias CompleteWithImageBlock = (_ selectedAsset:[UIImage]) -> Void
    public typealias CompleteWithVideoBlock = (_ selectedAsset:PHAsset?, _ localURL:NSURL?) -> Void
    
   public var assetsCallback:CompleteWithAssetsBlock?
   public var imagesCallback:CompleteWithImageBlock?
   public var videoCallBack:CompleteWithVideoBlock?
    
    //最大选择数，1表示单选
    var orignalData = false
    var maxSelectNum = 9
    var cropImageDelegate:cropImageProtocol?
    
    // 0 --> 照片 ; 1 --> 视频
    var selectType = 0 {
        didSet{
            setupModel()
        }
    }
    
   public init(parentViewModel:MVVM_BaseVCModel? ,selectType type:Int, maxSelectNum:Int , orignalData:Bool = false,cropImageDelegate:cropImageProtocol? = nil) {
        selectType = type
        self.maxSelectNum = maxSelectNum
        self.cropImageDelegate = cropImageDelegate
        self.orignalData = orignalData
        super.init(parentViewModel: parentViewModel)
    }
    
    let albumCellID = "albumCellID"
    override public func setupModel() {
        self.assetsResult.removeAll()
        self.assetCollectResult.removeAll()
        let fetchOp = PHFetchOptions()
        let result = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .any, options: fetchOp)
        result.enumerateObjects({ (x:AnyObject, _, _) in
            if let x = x as? PHAssetCollection{
                let result = PHAsset.fetchAssets(in: x, options: fetchOp)
                if result.count == 0{
                    return
                }
                if self.selectType == 0{
                    if x.assetCollectionSubtype == .smartAlbumVideos {
                      return
                    }
                }else if self.selectType == 1{
                    if x.assetCollectionSubtype != .smartAlbumVideos {
                       return
                    }
                }
                self.assetCollectResult.append(x)
                self.assetsResult.append(result as! PHFetchResult<AnyObject>)
            }
        })
        
    }
    
//    v
    override public func viewController(vcIndex: Int) -> MVVM_BaseViewController? {
        let x = YDPhotoController()
        return x
    }
    
    
    func getViewControllersArr() -> [UIViewController]?{
        let subType = selectType == 0 ? PHAssetCollectionSubtype.smartAlbumUserLibrary : PHAssetCollectionSubtype.smartAlbumVideos
        if let index = getIndex(with: subType){
            let model = YDPhotoShowAlbumVCModel(assetResult: assetsResult[index],parentVCModel: self)
            model.viewControllerTitle.value = assetCollectResult[index].localizedTitle
            model.maxSelectNum = maxSelectNum
            model.isUseOrignalData.value = orignalData
            return [self.creatViewController(vcIndex: 0)!, model.creatViewController(vcIndex: 0)!]
        }
        return [self.creatViewController()!]
    }
    
    public func getIndex(with subType:PHAssetCollectionSubtype) -> Int?{
            for (index, value) in assetCollectResult.enumerated(){
                if value.assetCollectionSubtype == subType {
                    return index
                }
            }
        return nil
    }
    
    
    //MARK: colloction
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return assetCollectResult.count 
    }
    
    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: albumCellID, for: indexPath)
        
        let albumModel = assetCollectResult[indexPath.row]
        cell.textLabel?.text = albumModel.localizedTitle! + " (" + String(assetsResult[indexPath.row].count) + ")"
//        cell.selectionStyle = .None
        return cell
    }
    
    public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let result = assetsResult[indexPath.row]
        let model = YDPhotoShowAlbumVCModel(assetResult: result, parentVCModel:  self)
        model.viewControllerTitle.value = assetCollectResult[indexPath.row].localizedTitle
        model.isUseOrignalData.value = orignalData
        model.maxSelectNum = maxSelectNum
        
        
        self.MVVM_navigationController?.pushVcModel(vcModel: model)
        
        tableView.deselectRow(at: indexPath as IndexPath, animated: true)
    }
}
